package jcode.project.mailserver.initdb;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.stereotype.Service;

import java.sql.ResultSet;
import java.sql.SQLException;


@Service
public class InitDB implements InitializingBean {

    private Logger logger = LoggerFactory.getLogger(InitDB.class);

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void afterPropertiesSet() throws Exception {
        this.initdb();
    }

    private void initdb() {
        if(! existTable("mail")){
            logger.info("初始化数据库");
            jdbcTemplate.execute("create table mail(id int(32) auto_increment, subject varchar(200), data CLOB, PRIMARY KEY (id));");
        }
    }

    private boolean existTable(String mail) {
        try {
            jdbcTemplate.query("select * from " + mail + " limit 1", new RowCallbackHandler() {
                @Override
                public void processRow(ResultSet rs) throws SQLException {

                }
            });
        }catch (BadSqlGrammarException e){
            String message = e.getCause().getMessage();
            if(message.contains("Table") && message.contains("not found")){
                return false;
            }
        }

        return true;
    }

}
